package com.sptpc.demo.controller;


import com.sptpc.demo.controller.requests.ModifyDrinkRequest;
import com.sptpc.demo.model.Student;
import com.sptpc.demo.service.IStudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Slf4j
@RestController
@RequestMapping("/stu")
public class StudentController {
    public IStudentService iStudentService;

    @GetMapping("/")
    @ResponseBody
    public List<Student> getAll(){
        List<Student> result = iStudentService.getAllStudents();
        return result;
    }

    @GetMapping("/{id}")
    public Student getStudent(@PathVariable Integer id){
        log.info("要查询的学生id: {}",id);
//        后期从数据库查询
        if (iStudentService.getStudentById(id)!=null) {
            return iStudentService.getStudentById(id);
        }else {
            return null;
        }
    }


    @PostMapping("/add")
    public Student addNewStudent(@RequestBody Student student){
        log.info("新增学生信息：{}",student);

        int studentId=student.getId();
        if (iStudentService.getStudentById(studentId) != null) {
            return null;
        }else {
            iStudentService.addNewStudent(student);
            return student;
        }
    }


    @DeleteMapping("/{id}")
    public String  deleteStudent(@PathVariable Integer id){
        log.info("要删除的学生id：{}",id);
        iStudentService.deleteStudent(id);
        return "删除操作成功";
    }


    @PutMapping("/")
    public Student modifyDrink(@RequestBody ModifyDrinkRequest request){
        log.info("修改学生：{}", request);

        Student student = iStudentService.getStudentById(request.getId());

        BeanUtils.copyProperties(request,student);
//        3.更新数据库
        iStudentService.updateStudent(student);
        return student;
    }



}
